#1. 简化数据框的批量操作
mtcars                         #数据

summary (mtcars$mpg)           #获取每加仑行驶英里数（mpg）变量的描述性统计量
plot(mtcars$mpg, mtcars$disp)  #绘制此变量与发动机排量（disp）的散点图
plot(mtcars$mpg, mtcars$wt)    #绘制此变量与车身重量（wt）的散点图

##以上代码可写成
attach(mtcars)
summary(mpg)
plot(mpg,disp)
plot(mpg,wt)
detach(mtcars)

##或写成
with(mtcars,{
     summary(mpg, disp, wt)
     plot(mpg, disp)
     plot(mpg, wt)
})   #局限性：变量仅在大括号内生效，特殊赋值符<<-替代标准赋值符（<-）可赋值至全局

with(mtcars,{
  a <- summary(mpg, disp, wt)
  plot(mpg, disp)
  plot(mpg, wt)
})
a

with(mtcars,{
  a <- summary(mpg, disp, wt)
  plot(mpg, disp)
  plot(mpg, wt)
  b <<- a
})
b
a


#2. 增加数据框的变量（列）
df1 <- data.frame(n    = rep(3,5),
                  mean = c(5.5, 9.8, 7.6, 8.1, 6.2),
                  sd   = c(0.2, 0.7, 1.1, 0.7, 0.1))

df1 

up <- df1$mean + df1$sd
up

df1$up <- df1$mean + df1$sd
df1


df1 <- data.frame(n    = rep(3,5),
                  mean = c(5.5, 9.8, 7.6, 8.1, 6.2),
                  sd   = c(0.2, 0.7, 1.1, 0.7, 0.1))

df1

within(df1, {
  up  = mean + sd
  down = mean - sd
  
})

df1
transform(df1, up  = mean + sd, down = mean - sd)
transform(df1, se = sd/(n^0.5))
transform(df1, se = sd/(n^0.5), up  = mean + se, down = mean - se)#不可以利用刚生成的列

library(dplyr)
mutate(df1, se = sd/(n^0.5), up  = mean + se, down = mean - se) #可以利用刚生成的列
